<?php

namespace app\admin\services;

use think\App;
use think\facade\Request;
use think\Service;
use think\facade\Session;
use app\admin\model\AdminUserModel;
use app\admin\model\ProblemModel;
use app\admin\model\GuestbookModel;
use app\admin\model\OperationModel;
use think\facade\Config;
class ProblemService extends Service
{
    public function __construct(Request $request = null, App $app = null)
    {
        parent::__construct($request, $app);
           $this->AdminUserModel = new AdminUserModel();
           $this->ProblemModel = new ProblemModel();
           $this->GuestbookModel = new GuestbookModel();
           $this->OperationModel = new OperationModel();
    }


    /**
     * @param 上传图片
     */
    public function ajaxUpload(){
        $type = strtolower(substr($_FILES['file']['name'],strrpos($_FILES['file']['name'],'.')+1));
        $allow_type = array('jpg','jpeg','gif','png');
        if(!in_array($type,$allow_type)) {
            return false;
        }
        $filename = time().'.'.$type;
        $paths = './static/upload';
        if(!file_exists($paths)){
            mkdir($paths,0777);
        }
        $path =$paths."/".$filename;
        $result = move_uploaded_file($_FILES["file"]["tmp_name"],$path);
        if($result){
            return ['status'=>1,'url'=>'/static/upload/'.$filename];
        }else{
            return ['status'=>0,'msg'=>'上传错误'];
        }
    }


    /**
     * @param 添加问题
     */
    public function add(){
        if(!Request::isPost()){
            return $this->_getResponse("NO_POST");
        }
        $post = Request::param();
        $post = $post['data'];
        if(empty($post['title'])){
            return ['status'=>1, "msg"=>"请输入标题"];
        }
        if(mb_strlen($post['title'])>15){
            return ['status'=>1, "msg"=>"标题输入过长"];
        }
        if(empty($post['like'])){
            return ['status'=>1, "msg"=>"请输入问题类型"];
        }
        if(empty($post['manga'])){
            return ['status'=>1, "msg"=>"请选择所属平台"];
        }
        if(empty($post['editorValue']) || !isset($post['editorValue'])){
            return ['status'=>1, "msg"=>"请输入问题内容"];
        }
        $userid = Session::get('uid','admin');
        $editorValue = htmlspecialchars($post['editorValue'],ENT_QUOTES);
        $data = [
            'title'=> $post['title'],
            'enable'=> $post['enable'],
            'classid'=>$post['like'],
            'warning'=>$post['liker'],
            'imgurl' => $post['banner'],
            'FounderID'=> $userid,
            'ProblemContent'=>$editorValue,
            'managid' => $post['manga']
        ];
        $rulest = $this->ProblemModel->addinect($data);
        if(!$rulest){
            return ['status'=>1, "msg"=>"操作失败"];
        }
        return $this->_getResponse("USER_ADD");
    }


    /**
     * @param 问题列表数据
     */
    public function lists(){
        $post = Request::param();
        $title = empty($post['title'])?"":$post['title'];
        $warning = empty($post['warning'])?"":$post['warning'];
        $state = empty($post['state'])?"":$post['state'];
        $start = empty($post['start'])?"":$post['start'];
        $end = empty($post['end'])?"":$post['end'];
        $page = isset($post['pageIndex'])?$post['pageIndex']:1;
        $limit = isset($post['pageSize'])?$post['pageSize']:15;
        $username = Session::get('username','admin');
        $tiao = [['username','eq',$username]];
        $Version = $this->AdminUserModel->findPw($tiao);
        $Versiontype = $Version['Versiontype'];
        $bios = [];
        if($warning==99){
            $warning =  [['a.warning','eq',1],['a.warning','eq',2],['a.warning','eq',3]];
        }else if($warning==""){
            $warning = false;
        }else{
            $bios = [['a.warning','eq',$warning]];
        }
        $tops = [];
        $Versiontypes = explode(',',Session::get('Versiontype','admin'));
        if(!in_array('2',$Versiontypes)){
            if($state==99){
                $tops = [['a.state','eq',0]];
            }else if($state==""){
                $state = false;
            }else if($state==100){
                $state = [['a.state','eq',0],['a.state','eq',1],['a.state','eq',2],['a.state','eq',3],['a.state','eq',4],['a.state','eq',5]];
            }else{
                $tops = [['a.state','eq',$state]];
            }
        }else{
            if($state==99){
                $tops = [['a.state','eq',0]];
            }else if($state==""){
                $state = false;
            }else if($state==100){
                $state = [['a.state','eq',0],['a.state','eq',1],['a.state','eq',2],['a.state','eq',3],['a.state','eq',4],['a.state','eq',5]];
            }else if($state==3){
                $tops = [['a.state','eq',3],['classid','neq',2]];
            }else if($state==4){
                if(Session::get('position','admin')==2 || Session::get('position','admin')==4 || Session::get('position','admin')==0 || Session::get('position','admin')==1 || Session::get('position','admin')==3){
                    $tops = [['a.stulit','eq',5]];
                }else{
                    $tops = [['a.state','eq',3],['classid','eq',2]];
                }
            }else if($state==5){
                    $tops = [['a.huluid','neq',""]];
            }else{
                $tops = [['a.state','eq',$state]];
            }
        }
        if(Session::get('uid','admin')==1){
            if(!empty($start)&&empty($end)){
                $where = [['a.addTime','>=',$start." 00:00:00"]];
            }else if(empty($start)&&!empty($end)){
                $where = [['a.addTime','<=',$end." 23:59:59"]];
            }else if(!empty($start)&&!empty($end)){
                $where = [['a.addTime','between',[$start." 00:00:00",$end." 23:59:59"]]];
            }else{
                $where = [['a.addTime','gt',date('Y-m-d')]];
            }
            if($start=="" && $end==""){
                $where =[];
                $wheres = [['a.title','like','%'.$title.'%'],['state','eq',0]];
            }else{
                $wheres = [['a.title','like','%'.$title.'%']];
            }
        }else{
            if(!empty($start) && empty($end)){
                $where = [['a.addTime','>=',$start." 00:00:00"]];
            }else if(empty($start)&&!empty($end)){
                $where = [['a.addTime','<=',$end." 23:59:59"]];
            }else if(!empty($start)&&!empty($end)){
                $where = [['a.addTime','between',[$start." 00:00:00",$end." 23:59:59"]]];
            }else {
                $where = [['a.addTime','gt',date('Y-m-d')]];
            }
            if($start=="" && $end==""){
                $where =[];
                $wheres = [['a.title','like','%'.$title.'%'],['classid','in',$Versiontype],['state','eq',$state]];
            }else{
                $wheres = [['a.title','like','%'.$title.'%'],['classid','in',$Versiontype]];
            }
        }
        if(!empty($warning) && $start=="" && $end==""){
            $where = [];
            if(Session::get('uid','admin')==1){
                $wheres = [['a.title','like','%'.$title.'%']];
            }else{
                $wheres = [['a.title','like','%'.$title.'%'],['classid','in',$Versiontype]];
            }
        }
        if(!empty($state) && $start=="" && $end==""){
            $where = [];
            if(Session::get('uid','admin')==1){
                $wheres = [['a.title','like','%'.$title.'%']];
            }else{
                $wheres = [['a.title','like','%'.$title.'%'],['classid','in',$Versiontype]];
            }
        }
        $list = $this->ProblemModel->problist($where,$wheres,$tops,$bios,$page,$limit);
        $counts = $this->ProblemModel->county($where,$tops,$bios,$wheres);
        $array = [];
        foreach ($list as $value){
            if($value['classid']!=2){
                if($value['huluid']!=""){
                    $value['stutsa'] = stuste($value['state'])."(".$value['huluid'].")";
                    $value['groupd'] = "";
                }else{
                    $value['stutsa'] = stuste($value['state']);
                    if($value['groupd']==0){
                        $value['groupd'] = groutime($value['groupd'],$value['id']);
                    }else{
                        $value['groupd'] = $value['groupd']."天"."(".date("Y-m-d",strtotime($value['addTime'])+3600*24*$value['groupd']).")";
                    }
                }
            }else{
                if($value['huluid']!=""){
                    $value['stutsa'] = stusteto($value['state'])."(".$value['huluid'].")";
                    $value['groupd'] = "";
                }else{
                    $value['stutsa'] = stusteto($value['state']);
                    if($value['groupd']==0){
                        $value['groupd'] = groutime($value['groupd'],$value['id']);
                    }else{
                        $value['groupd'] = $value['groupd']."天"."(".date("Y-m-d",strtotime($value['addTime'])+3600*24*$value['groupd']).")";
                    }
                }
            }
            $value['status'] = disa($value['enable']);
            if($value['classid']==2){
                $value['Processing'] = jinduto($value['Processing']);
            }else{
                $value['Processing'] = jindu($value['Processing']);
            }
            $value['titoe'] = mb_substr($value['title'],0,15);
            $value['title'] = "<a  style='text-decoration:underline' href='/admin/problem/auxiliar?id=".$value['id']."'>".$value['titoe']."</a>";
            if($value['warning']==1){
                $value['warning'] = warn($value['warning']);
                $value['warin'] = "<button class='layui-btn layui-btn-mini'>".$value['warning']."</button>";
            }
            if($value['warning']==2){
                $value['warning'] = warn($value['warning']);
                $value['warin'] = "<button class='layui-btn layui-btn-normal layui-btn-mini'>".$value['warning']."</button>";
            }
            if($value['warning']==3){
                $value['warning'] = warn($value['warning']);
                $value['warin'] = "<button class='layui-btn layui-btn-danger layui-btn-mini'>".$value['warning']."</button>";
            }
//            $value['curl'] = $value['steate']==2?"":$value['curl'];
//            $value['ProblemContent'] = html_entity_decode($value['ProblemContent'],ENT_QUOTES );
//            $value['ProblemContent'] = substr($value['ProblemContent'],0,50).".......";
            $value['uid'] = empty($value['uid'])?"":$value['uid'];
            $value['counts'] = empty($counts)?"":$counts;
            $value['username'] = empty($value['username'])?"":$value['username'];
            $value['addTime'] = date('m-d H:i',strtotime($value['addTime']));
            $value['updateTime'] = date('m-d H:i',strtotime($value['updateTime']));
            $array[] = $value;
        }
        if(empty($list)){
            $data['rel'] = false;
            $data['msg'] = "暂无数据";
        }else{
            $data['rel'] = true;
            $data['msg'] = "获取成功";
        }
        $data['list'] = $array;
        $data['count'] = $counts;
        return $data;
    }


    /**
     * @param 禁用/启用
     */
    public function examine(){
        if(!Request::isPost()){
            return $this->_getResponse("NO_POST");
        }
        $post = Request::param();
        $where = [['id','eq',$post['id']]];
        $rustl = $this->ProblemModel->exbut($where);
        if(!$rustl){
            return $this->_getResponse("NUKNOW_EORRE");
        }
        $enable = $rustl['enable'];
        if($enable==1){
            $data = ['enable'=> 2];
            $oper['actionInfo']= "禁用问题";
        }else{
            $data = ['enable'=> 1];
            $oper['actionInfo']= "启用问题";
        }
        $listos = $this->ProblemModel->eidtion($where,$data);
        if(!$listos){
            return $this->_getResponse("CAOZUO_ERROR");
        }
        $uid = Session::get('uid','admin');
        $oper['actionTime'] = time();
        $oper['actionIp'] = getIp();
        $oper['uid'] = $uid;
        $oper['username'] = Session::get('username','admin');
        $alllog = $this->OperationModel->addlog($oper);
        if(!$alllog){
            return $this->_getResponse("CAOZUO_ERROR");
        }
        return $this->_getResponse("ENBES_DATE");
    }


    /**
     * @param 删除问题
     */
    public function del(){
        if(!Request::isPost()){
            return $this->_getResponse("NO_POST");
        }

        $post = Request::param();
        if(!$post['id']){
            return $this->_getResponse("PARAM_EORRE");
        }
        $id = $post['id'];
        $ruledt = $this->ProblemModel->delect($id);
        if(!$ruledt){
            return $this->_getResponse("CAOZUO_ERROR");
        }
        return $this->_getResponse("DELETE_DATE");
    }


    /**
     * @param 获取当前修改信息
     */
    public function eddata(){
        $post = Request::param();
        if(empty($post['id'])){
            return $this->_getResponse("PARAM_EORRE");
        }
        $id = $post['id'];
        $data = $this->ProblemModel->editlist($id);
        if(!$data){
            return $this->_getResponse("DATA_ERROR");
        }
       return $data;
    }


    /**
     * @param 修改问题
     */
    public function editonst(){
        if(!Request::isPost()){
            return $this->_getResponse("NO_POST");
        }
        $post = Request::param();
        if(empty($post['data']['title'])){
            return ['status'=>1, "msg"=>"请输入标题"];
        }
        if(empty($post['data']['like'])){
            return ['status'=>1, "msg"=>"请输入问题类型"];
        }
        if(empty($post['data']['manga'])){
            return ['status'=>1, "msg"=>"请选择所属平台"];
        }
        $editorValue = htmlspecialchars($post['activityContent']);
        $data = [
            'title'=> $post['data']['title'],
            'enable'=> $post['data']['enable'],
            'classid'=> $post['data']['like'],
            'warning'=>$post['data']['liker'],
            'imgurl' => $post['data']['banner'],
            'ProblemContent'=>$editorValue,
            'managid' => $post['data']['manga'],
            'updateTime' => date("Y-m-d,H:i:s",time())
        ];
        $where = [["id",'eq',$post['data']['probleid']]];
        $rulest = $this->ProblemModel->edisont($where,$data);
        if(!$rulest){
            return ['status'=>1, "msg"=>"修改失败"];
        }

        return $this->_getResponse("EDIT_SUCCESS");
    }


    /**
     * @param 一键确认
     */
    public function deatr(){
        if(!Request::isPost()){
            return $this->_getResponse("NO_POST");
        }
        $post = Request::param();
        $position = Session::get('position', 'admin');
        $uid = Session::get('uid', 'admin');
        $prtype = $post['state'];
        $where = [['state','eq',$prtype],['classid','neq',2]];
        $data = [];
        if($position==2){
            $state = 2;
            $data = [
                'state'=>$state,
                'Processing'=>$state
            ];
        }
        if($position==3){
            $ruit = $this->ProblemModel->emptyu($where); //判断处理人是否为空
            $state = $ruit['uid']==0?1:3;
            if($ruit['uid']==0){
                $data = [
                    'state'=>$state,
                    'uid'=>$uid,
                    'Processing'=>$state
                ];
            }else{
                $data = [
                    'state'=>$state,
                    'Processing'=>$state
                ];
            }
        }
        if($position==1){
            $state = 1;
            $data = [
                'state'=>$state,
                'uid'=>$uid,
                'Processing'=>$state
            ];
        }
        if($position==4){
            if($prtype==2){
                $state = 3;
            }else{
                $state = 4;
            }
            $data = [
                'state'=>$state,
                'Processing'=>$state,
                'stulit'=>5
            ];
        }
        $rulst = $this->ProblemModel->confirmlist($where,$data);
        if(!$rulst){
            return $this->_getResponse("CAOZUO_ERROR");
        }
        return $this->_getResponse("CONFIRM_SUCCESS");
    }


    /**
     * @param 确认问题
     */
    public function confirm(){
        if(!Request::isPost()){
            return $this->_getResponse("NO_POST");
        }
        $post = Request::param();
        $position = Session::get('position', 'admin');
        $uid = Session::get('uid', 'admin');
        $proid = $post['id'];
        $prtype = $post['bd'];
        $where = [['id','eq',$proid]];
        $data = [];
        if($position==2){
            $state = 2;
            $data = [
                'state'=>$state,
                'Processing'=>$state
            ];
        }
        if($position==3){
            $ruit = $this->ProblemModel->emptyu($where); //判断处理人是否为空
            $state = $ruit['uid']==0?1:3;
            if($ruit['uid']==0){
                $data = [
                    'state'=>$state,
                    'uid'=>$uid,
                    'Processing'=>$state
                ];
            }else{
                $data = [
                    'state'=>$state,
                    'Processing'=>$state
                ];
            }
        }
        if($position==1){
            $state = 1;
            $data = [
                'state'=>$state,
                'uid'=>$uid,
                'Processing'=>$state
            ];
        }
        if($position==4){
            if($prtype==2){
                $state = 3;
            }else{
                $state = 4;
            }
            $data = [
                'state'=>$state,
                'Processing'=>$state,
                'stulit'=>5
            ];
        }
        $rulst = $this->ProblemModel->confirmlist($where,$data);
        if(!$rulst){
            return $this->_getResponse("CAOZUO_ERROR");
        }
        return $this->_getResponse("CONFIRM_SUCCESS");
    }


    /**
     * @param 问题重置
     */
    public function restL(){
        if(!Request::isPost()){
            return $this->_getResponse("NO_POST");
        }
        $post = Request::param();
        $prid = $post['proid'];
        $data = ['state'=> 0,'Processing'=>0,'uid'=>0,'groupd'=>0,'huluid'=>null,'stulit'=>0];
        $rulst = $this->ProblemModel->restls($prid,$data);
        if(!$rulst){
            return $this->_getResponse("CAOZUO_ERROR");
        }
        $uid = Session::get('uid','admin');
        $oper['actionTime'] = time();
        $oper['actionIp'] = getIp();
        $oper['uid'] = $uid;
        $oper['actionInfo']= "重置问题";
        $oper['username'] = Session::get('username','admin');
        $alllog = $this->OperationModel->addlog($oper);
        if(!$alllog){
            return $this->_getResponse("CAOZUO_ERROR");
        }
        return $this->_getResponse("ENBES_DATE");
    }

    /**
     * @param 提交留言
     * @param 嬷嬷QK
     */
    public function emailmomo(){
        if(!Request::isPost()){
            return $this->_getResponse("NO_POST");
        }
        $post = Request::param();
        $post = $post['data'];
        $uid = Session::get("uid","admin");
        if(empty($post['editorValue'])){
            return ["status"=>1,"msg"=>"请输入留言信息"];
        }
        if(empty($post['probid'])){
            return $this->_getResponse("PARAM_EORRE");
        }
        $vdort = mb_strlen($post['editorValue']);
        if($vdort>200){
            return ["status"=>1,"msg"=>"留言内容请控制在200字符以内。"];
        }
        $editorValue = htmlspecialchars($post['editorValue']);
        $data = [
            'userid'=>$uid,
            'probleid' => $post['probid'],
            'Content' => $editorValue
        ];
        $rulset = $this->GuestbookModel->addemile($data);
        if(!$rulset){
            return $this->_getResponse("CAOZUO_ERROR");
        }
        return $this->_getResponse("EMLIE_SUCCESS");
    }


    /**
     * @param 获取当前留言信息
     */
    public function emaillist(){
        $post = Request::param();
        if(empty($post['id'])){
            return $this->_getResponse("PARAM_EORRE");
        }
        $probleid = $post['id'];
        $where = [['a.probleid','eq',$probleid]];
        $rulest = $this->GuestbookModel->conectlist($where);
        $array =[];
        foreach ($rulest as $value){
            $value['position'] = opstion($value['position']);
            $array[] = $value;
        }
        return $array;
    }


    /**
     * @param 获取问题列表
     */
    public function pridlist(){
        $data = $this->ProblemModel->sellist();
        return $data;
    }


    /**
     * @param $id
     * @param 获取问题详情列表
     */
    public function pkeion(){
        $id = Request::param('id');
       $data = $this->ProblemModel->details($id);
        return $data;
    }


    /**
     * @param 设置处理天数
     */
    public function groudtime(){
        if(!Request::isPost()){
            return $this->_getResponse("NO_POST");
        }
        $post = Request::param();
        if(empty($post['days']) || empty($post['id'])){
            return $this->_getResponse("NUKNOW_EORRE");
        }
        $where = [['id','eq',$post['id']]];
        $data = ['groupd'=> $post['days']];
        $rulst = $this->ProblemModel->groudtime($where,$data);
        if(!$rulst){
            return $this->_getResponse("CAOZUO_ERROR");
        }
        return  $this->_getResponse("ENBES_DATE");
    }


    /**
     * @param 显示隐藏问题
     */
    public function showdata(){
        if(!Request::isPost()){
            return $this->_getResponse("NO_POST");
        }
        $post = Request::param();
        $where = [['id','eq',$post['pid']]];
        if($post['show']==2){
            $data = ['show'=> 1];
        }else{
            $data = ['show'=> 2];
        }
        $rulet = $this->ProblemModel->showdata($where,$data);
        if(!$rulet){
            return $this->_getResponse("CAOZUO_ERROR");
        }
        return  $this->_getResponse("ENBES_DATE");
    }


    /**
     * @param 待解决问题数量
     */
    public function condata(){
        $typeid = Session::get('Versiontype','admin');
        $position = Session::get('position','admin');
        $where = [['classid','in',$typeid],['state','lt',$position],['state','neq',5]];
        $rulst = $this->ProblemModel->conunty($where);
        return $rulst;
    }


    /**
     * @param 忽略问题
     */
    public function huledata(){
        if(!Request::isPost()){
            return $this->_getResponse("NO_POST");
        }
        $post = Request::param();
        $id = $post['proid'];
        $where = [['id','eq',$id]];
        $username = Session::get('username','admin');
        $potionds = $this->ProblemModel->mosdelt($id);
        if(!empty($potionds['huluid'])){
            return $this->_getResponse("WENT_HULV");
        }
        if($potionds['classid']==2){
            $data = ['state'=> 4,'huluid'=>$username];
        }else{
            $data = ['state'=> 5,'huluid'=>$username];
        }
        $rulst = $this->ProblemModel->huledata($where,$data);
        if(!$rulst){
            return $this->_getResponse("CAOZUO_ERROR");
        }
        return $this->_getResponse("ENBES_DATE");
    }



//    public function adseino(){
//        $data = $this->ProblemModel->adseino();
//        if(!$data){
//            return  $this->_getResponse("CAOZUO_ERROR");
//        }else{
//            halt($data);
//        }
//    }


    /**
     * @param $key
     * @param array $data
     * @return mixed
     */
    protected function _getResponse($key, $data = [])
    {
        $maps = [
            "SUCCESS" => ["status" => 0, "msg" => "sccuess", "data" => $data],
            "USER_ADD" => ["status" => 0, "msg" => "添加成功", "data" => $data],
            "ENBES_DATE" => ["status" => 0, "msg" => "操作成功", "data" => $data],
            "DELETE_DATE" => ["status" => 0, "msg" => "删除成功", "data" => $data],
            "PARAM_EORRE" => ["status" => 1, "msg" => "参数错误", "data" => $data],
            "NUKNOW_EORRE" => ["status" => 2, "msg" => "未知错误", "data" => $data],
            "DATA_ERROR" => ["status" => 7, "msg" => "数据不存在", "data" => $data],
            "AUTH_EORRE" => ["status" => 3, "msg" => "权限不足", "data" => $data],
            "NO_POST" => ["status" => 4, "msg" => "非法请求", "data" => $data],
            "USER_ERROR" => ["status" => 5, "msg" => "用户名已存在", "data" => $data],
            "CAOZUO_ERROR" => ["status" => 6, "msg" => "操作失败", "data" => $data],
            "WENT_HULV" => ["status" => 6, "msg" => "该问题已忽略", "data" => $data],
            "EDIT_SUCCESS" => ["status" => 0, "msg" => "修改成功", "data" => $data],
            "CONFIRM_SUCCESS" => ["status" => 0, "msg" => "确认成功", "data" => $data],
            "EMLIE_SUCCESS" => ["status" => 0, "msg" => "留言成功", "data" => $data]
        ];
        return $maps[$key];
    }
}